package queue;

import java.util.Scanner;

public class CircleQueue {
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        char key = ' ';
        boolean loop = true;
        cleQue cleQue = new cleQue(4);
        while (loop) {
            System.out.println("a添加数据");
            System.out.println("s显示数据");
            System.out.println("g获得数据");
            System.out.println("h显示第一个数据");
            System.out.println("输入命令：");
            key = s.next().charAt(0);
            switch (key) {
                case 'a' :
                    System.out.println("输入添加的数据");
                    int i = s.nextInt();
                    cleQue.add(i);
                    break;
                case 's':
                    cleQue.show();
                    break;
                case 'g':
                    int i1 = 0;
                    try {
                        i1 = cleQue.get();
                        System.out.println(i1);
                    } catch (RuntimeException e) {
                        String message = e.getMessage();
                        System.out.println(message);
                    }
                    break;
                case 'h':
                    cleQue.headShow();
                    break;
                case 'e':
                    loop = false;
                    break;
            }
        }
    }
}
class cleQue{
    private int maxSize;
    private int front;
    private int rear;
    private int[] arr;
    public cleQue(int i) {
        maxSize = i;
        arr = new int[maxSize];
    }
    public boolean isFull() {
        return (rear+1)%maxSize==front;
    }
    public boolean isEmpty() {
        return rear==front;
    }
    //往环形队列中添加元素
    public void add(int i) {
        if(isFull()) {
            System.out.println("数组已满，无法添加");
            return;
        }
        arr[rear] = i;
        rear = (rear+1)%maxSize;
    }
    //取出环形队列中的一个元素
    public int get() {
        if(isEmpty()) {
            throw new RuntimeException("数组已空，无法取出");
        }
        int value = arr[front];
        front = (front+1)%maxSize;
        return value;
    }
    public void show() {
        if(isEmpty()) {
            System.out.println("数组已空，请添加");
            return;
        }
        for (int i = front; i < front+size(); i++) {
            System.out.print(String.format("arr[%d]是%d\n" ,i%maxSize,arr[i%maxSize]));
        }
    }
    public int size() {
        return (rear+maxSize-front)%maxSize;
    }
    //显示环形队列中的第一个元素
    public int headShow() {
        return arr[front];
    }
}
